<template>
  <el-upload
    class="avatar-uploader"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img
      v-if="imageUrl || externalImageUrl"
      :src="imageUrl || externalImageUrl"
      class="avatar"
    />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";

const imageUrl = ref("");

// 定义接收的 props
const props = defineProps({
  externalImageUrl: String,
});
// 定义回传数据
const emit = defineEmits(["update:image", "file-uploaded"]);

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // 仅用于创建预览
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  // 发射事件至父组件，包含文件数据
  emit("file-uploaded", uploadFile.raw);
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const allowedTypes = ["image/jpeg", "image/png", "image/svg+xml"];
  if (!allowedTypes.includes(rawFile.type)) {
    ElMessage.error("Avatar picture must be in JPG, PNG, or SVG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size cannot exceed 2MB!");
    return false;
  }
  return true;
};
</script>

<style scoped>
.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #8c939d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
</style>
